
from azs_https import AzsHttpClient


class TokenInfo:
    def __init__(self, base_url: str, username: str, password: str):
        if base_url.endswith("/"):
            base_url = base_url[:-1]
        self.base_url = base_url
        self.username = username
        self.password = password
        self.token = None


    def get_token(self) -> str:
        try:
            self._get_user_language()
        except Exception:
            self.token =  self.login()
        return self.token


    def _get_user_language(self):
        url = f"{self.base_url}/api/admin/user/get-user-language"
        headers = {"Authorization": self.token}
        try:
            httpclient = AzsHttpClient()
            response =  httpclient.get(url=url, headers=headers)
            return response
        except Exception as e:
            raise e


    def login(self) -> str:
        url = f"{self.base_url}/api/token/login-pw"
        httpclient = AzsHttpClient()
        res =  httpclient.post(url=url, params={"username": self.username, "password": self.password})
        self.token = res['token']
        return self.token


    def test(self):
        httpclient = AzsHttpClient()
        try:
            res =  httpclient.post(url='http://dev.azures.cn:28888/api/token/login-pw',
                                        params={"username": 'auto_test', "password": "Qwer123#@!"})
            print(res)
        finally:
            print(1)


if __name__ == '__main__':
    tokenInfo = TokenInfo('http://dev.azures.cn:28888', 'auto_test', 'Qwer123#@!')
    tokenInfo.login()
